package com.taiji.dianthus.controller.sms;

import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.domain.sms.SmsGroup;
import com.taiji.dianthus.domain.sms.SmsGroupUser;
import com.taiji.dianthus.domain.sms.SmsInfo;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.service.sms.SmsGroupService;
import com.taiji.dianthus.service.sms.SmsGroupUserService;
import com.taiji.dianthus.service.sms.SmsInfoService;
import com.taiji.dianthus.service.sys.OrgService;
import com.taiji.dianthus.service.sys.SysLogService;
import com.taiji.dianthus.sms.HttpSendSmsService;
import com.taiji.dianthus.sms.Sdk2SMSSendService;
import com.taiji.dianthus.util.IPUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

import static com.taiji.dianthus.common.Constant.LOG_OPERATION_QUERY;
import static com.taiji.dianthus.common.Constant.LOG_OPERATION_SAVE;

/**
 * @ClassName smsInfoController
 * @Description 群发消息
 * @Author H.M
 * @Date 2020/7/15
 */
@RequestMapping(value = "/sms/sendGroup")
@Controller
public class SmsInfoGroupViewController extends BasicController {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private SmsInfoService smsInfoService;
    @Autowired
    private SmsGroupService groupService;
    @Autowired
    private SmsGroupUserService groupUserService;

    /**
     * 发送信息页面
     * 发送箱-编辑 跳转群发页面 带参数 flag  startDate  endDate currentPage groupId
     * 草稿箱-编辑  跳转群发页面flag=drafts  startDate  endDate currentPage groupId
     * 编辑分组-跳转群分组页面-再返回到页面带参数  topic  content
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/sendIndex")
    public String sendMessageIndex(HttpServletRequest request, Model model, String id, String flag, String groupId, String startDate, String endDate, Integer currentPage, String topic, String content) {
        DSysUser user = currentUser();
        SmsInfo info = null;
        if (!StringUtils.isEmpty(id)) {
            info = smsInfoService.getOne(id);
        } else {
            info = new SmsInfo();
            info.setMsgSubject(topic);
            info.setMsgContent(content);
        }
        if (!StringUtils.isEmpty(groupId) && !"".equals(groupId)) {
            info.setSmsGroupId(groupId);
        }
        if (!StringUtils.isEmpty(flag)) {//判断页面显示取消还是返回  同时判断返回哪个页面
            if (("drafts").equals(flag)) {
                String url = "/sms/drafts/list?pageSize=10";
                if (!StringUtils.isEmpty(startDate)) {
                    url += "&startDate=" + startDate;
                }
                if (!StringUtils.isEmpty(endDate)) {
                    url += "&endDate=" + endDate;
                }
                if (currentPage != null) {
                    url += "&currentPage=" + currentPage;
                }
                model.addAttribute("url", url);
            } else {
                String url = "/sms/info/list?pageSize=10";
                if (!StringUtils.isEmpty(startDate)) {
                    url += "&startDate=" + startDate;
                }
                if (!StringUtils.isEmpty(endDate)) {
                    url += "&endDate=" + endDate;
                }
                if (currentPage != null) {
                    url += "&currentPage=" + currentPage;
                }
                model.addAttribute("url", url);
            }
        }
        List<SmsGroup> groupList = groupService.getAllGroupNoPage(user.getId());
        model.addAttribute("data", info);
        model.addAttribute("flagStr", flag);
        model.addAttribute("groupList", groupList);
        model.addAttribute("currentUser", user);
        model.addAttribute("menus", listMenu());
        sysLogService.save(user, LOG_OPERATION_QUERY,
                IPUtil.getIpAddr(request), "查询群发页面", 1, "查询成功");
        return "/pages/sms/sendGroupMessage";
    }

    @ResponseBody
    @RequestMapping("/sendMsg")
    public BusinessMessage sendMsg(HttpServletRequest request, @RequestBody SmsInfo smsInfo) {
        smsInfo.setSendUserId(currentUser().getId());
        List<SmsGroupUser> groupUserList = groupUserService.getAllUserListByGroupIdNotPage(smsInfo.getSmsGroupId());
        List<String> userPhones = groupUserList.stream().map(SmsGroupUser::getUserPhone).collect(Collectors.toList());
        smsInfo.setReceiveUserPhone(StringUtils.strip(userPhones.toString().replaceAll(" ", ""), "[]"));
        smsInfo.setReceiveBookUserPhone(StringUtils.strip(userPhones.toString().replaceAll(" ", ""), "[]"));
        SmsGroup group = groupService.getOneById(smsInfo.getSmsGroupId());
        smsInfo.setReceiveBookUserName(group.getGroupName());
        BusinessMessage message = smsInfoService.sendDSMS(smsInfo);
        sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                IPUtil.getIpAddr(request), "群发短信", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    @ResponseBody
    @RequestMapping("/saveDraft")
    public BusinessMessage saveDraft(HttpServletRequest request, @RequestBody SmsInfo smsInfo) {
        smsInfo.setSendUserId(currentUser().getId());
        String groupId = smsInfo.getSmsGroupId();
        if (!StringUtils.isEmpty(groupId) && !"".equals(groupId)) {
            List<SmsGroupUser> groupUserList = groupUserService.getAllUserListByGroupIdNotPage(smsInfo.getSmsGroupId());
            List<String> userPhones = groupUserList.stream().map(SmsGroupUser::getUserPhone).collect(Collectors.toList());
            smsInfo.setReceiveUserPhone(StringUtils.strip(userPhones.toString(), "[]"));
            smsInfo.setReceiveBookUserPhone(StringUtils.strip(userPhones.toString(), "[]"));
            SmsGroup group = groupService.getOneById(smsInfo.getSmsGroupId());
            smsInfo.setReceiveBookUserName(group.getGroupName());
        }
        BusinessMessage message = smsInfoService.save(smsInfo);
        sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                IPUtil.getIpAddr(request), "保存群发草稿", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    /**
     * 定时短信
     *
     * @param request
     * @param smsInfo
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendTimingMsg")
    public BusinessMessage sengTimingMsg(HttpServletRequest request, @RequestBody SmsInfo smsInfo) {
        smsInfo.setSendUserId(currentUser().getId());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(smsInfo.getMsgTime());
        calendar.set(Calendar.SECOND, 0);
        smsInfo.setMsgTime(calendar.getTime());
        String groupId = smsInfo.getSmsGroupId();
        if (!StringUtils.isEmpty(groupId) && !"".equals(groupId)) {
            List<SmsGroupUser> groupUserList = groupUserService.getAllUserListByGroupIdNotPage(smsInfo.getSmsGroupId());
            List<String> userPhones = groupUserList.stream().map(SmsGroupUser::getUserPhone).collect(Collectors.toList());
            smsInfo.setReceiveUserPhone(StringUtils.strip(userPhones.toString(), "[]"));
            smsInfo.setReceiveBookUserPhone(StringUtils.strip(userPhones.toString(), "[]"));
            SmsGroup group = groupService.getOneById(smsInfo.getSmsGroupId());
            smsInfo.setReceiveBookUserName(group.getGroupName());
        }
        BusinessMessage message = smsInfoService.save(smsInfo);
        // BusinessMessage message = sdk2SMSSendService.sendDSMS(smsInfo, false);
        sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                IPUtil.getIpAddr(request), "保存定时短信息", message.success ? 1 : 0, message.getMsg());
        return message;
    }

}
